﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.DataVisualization.Charting;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using System.Data.SqlClient;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class CountryStatistics : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.CountryStatistics_PageTitle;
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                Response.Redirect("~/Default.aspx");

            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];


            if (ou.UserAccessLevel != ("5"))
            {
                Response.Redirect("~/Default.aspx");
            }

            if (!IsPostBack)
            {
                if (Request.QueryString["Country"] != null)
                {
                    BindCountry(Request.QueryString["Country"]);
                }
                else
                    BindCountry("10");

                AllCountriesStatsGridview.UseAccessibleHeader = true;
                AllCountriesStatsGridview.HeaderRow.TableSection = TableRowSection.TableHeader;
            }

        }

        protected void BindCountryFromDDL(object sender, EventArgs e)
        {
             BindCountry(NationalityDropDownList.SelectedValue);
        }

        protected void CreateChartButtonClick(object sender, EventArgs e)
        {
            ChartPanel.Visible = true;
            BindChartData();
        }

        private void BindCountry(string CountryId)
        {
            try
            {
                CountryDetailsDS.SelectParameters.Clear();
                CountryDetailsDS.SelectParameters.Add("CountryId", CountryId);

                CountryDetailsGrid.DataSourceID = "CountryDetailsDS";
                CountryDetailsGrid.DataBind();
                if (CountryId != "10")
                {
                    GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                    CountryTitleLabel.Text = "Detailed statistics in " + GND.ReadNivdalStringData("CountryId", "Nivdal_GetCountryNameByIdProc", CountryId);
                }
                else
                {
                    CountryTitleLabel.Text = "";
                }
            }
            catch { }

        }

        private void BindChartData()
        {
            string ChartType = ChartTypeDDL.SelectedValue;
            Chart1.Series.Clear();
            using (SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                foreach (GridViewRow row in AllCountriesStatsGridview.Rows)
                {
                    if ((row.FindControl("AddToChartCheckBox") as CheckBox).Checked)
                    {
                        string CountryId = ((row.FindControl("CountryIdHiddenField") as HiddenField).Value);
                        string CountryName = ((row.FindControl("CountryLink") as HyperLink).Text);
                        SqlCommand cmd = new SqlCommand("Nivdal_GetCountryStatsGraph", myConnection);
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("StatNumber", ChartType);
                        cmd.Parameters.AddWithValue("Country", CountryId);

                        SqlDataReader reader;
                        
                        try
                        {
                            myConnection.Open();
                            reader = cmd.ExecuteReader();
                            if (reader.HasRows)
                            {
                                Chart1.Series.Add(CountryName);
                                double minimum = 0, maximum = 0;
                                Chart1.Series[CountryName].ChartType = SeriesChartType.Line;
                                Chart1.Series[CountryName].BorderWidth = 2;
                                Chart1.Series[CountryName].ShadowOffset = 2;
                                Chart1.Series[CountryName].XValueType = ChartValueType.DateTime;
                                while (reader.Read())
                                {
                                    double date = reader.GetDateTime(0).ToOADate();

                                    if ((minimum == 0) || (minimum > date))
                                        minimum = date;
                                    if ((maximum == 0) || (maximum < date))
                                        maximum = date;
                                    
                                    Chart1.Series[CountryName].Points.AddXY(date, double.Parse(reader.GetDecimal(1).ToString()));                                    
                                }
                                Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = minimum;
                                Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = maximum;
                            }
                        }
                        catch { }
                        finally
                        {
                            myConnection.Close();
                        }
                    }
                }

            }

            Chart1.Titles[0].Text = ChartTypeDDL.SelectedItem.Text + " chart";
            
        }

        protected void CheckAllButtonClick(object sender, EventArgs e)
        {
            foreach (GridViewRow r in AllCountriesStatsGridview.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    (r.FindControl("AddToChartCheckBox") as CheckBox).Checked = true;
                }
            }
        }
        protected void ClearAllButtonClick(object sender, EventArgs e)
        {
            foreach (GridViewRow r in AllCountriesStatsGridview.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    (r.FindControl("AddToChartCheckBox") as CheckBox).Checked = false;
                }
            }
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }
    }
}